package serializableObj;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializableObjDemo {

	public static void main(String[] args) {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			// 创建对象系列化所需要的输出流
			fos = new FileOutputStream("e:/t01/stu.txt");
			oos = new ObjectOutputStream(fos);
			// 创建对象
			Students stu = new Students(1,22,"张三","123456");
			System.out.println("**********系列化对象前**********");
			System.out.println("id:" + stu.getId());
			System.out.println("年龄:" + stu.getAge());
			System.out.println("名字:" + stu.getName());
			System.out.println("密码:" + stu.getPw());
			// 系列化对象
			oos.writeObject(stu);
			
			// 创建对象反系列化所需要的输入流
			fis = new FileInputStream("e:/t01/stu.txt");
			ois = new ObjectInputStream(fis);
			// 反系列化对象
			Students stu1 = (Students)ois.readObject();
			System.out.println("**********反系列化对象后**********");
			System.out.println("id:" + stu1.getId());
			System.out.println("年龄:" + stu1.getAge());
			System.out.println("名字:" + stu1.getName());
			System.out.println("密码:" + stu1.getPw());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			// 关闭流
			try {
				ois.close();
				fis.close();
				oos.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}

	}

}
